package com.sulent.frame.file.utils;

import com.google.common.collect.Multimap;
import com.google.common.net.MediaType;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.InitiateMultipartUploadResult;
import io.minio.messages.Part;
import lombok.SneakyThrows;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SubFileDemo
 * @Description: TODO
 * @Author Submerge.
 * @Since 2024/2/2 17:52
 * @Version 1.0
 */
public class SubFileDemo {




    public static void main(String[] args) throws ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, IOException, InvalidKeyException, XmlParserException, InvalidResponseException, InternalException {

        /**
         *         MinioFileServer fileServer =  new MinioFileServer("http://172.16.0.16:9000/", "rcmL8t0EfcmaGrEQ", "0CDZzmRFlqLaRnoufn177wycXlin3lt1", "ai-model");
         */
        String endpoint= "http://172.16.0.16:9000/";
         String accessKey="rcmL8t0EfcmaGrEQ";
         String secretKey="0CDZzmRFlqLaRnoufn177wycXlin3lt1";
         String bucketName="ai-model";

         //源文件
        File f = new File("D:\\data\\merge\\产品推广.pptx");
        long contentLength = f.length(); //源文件长度
        long partSize = 5 * 1024 * 1024; // 分片大小




        //1、创建分片的minio客户端
        SubMinioClient subMinioClient = new SubMinioClient(MinioAsyncClient.builder().endpoint(endpoint).credentials(accessKey,secretKey).build());


        //2，初始化分片上传任务
        String objectName = "sub/test1/222.pptx";
        CreateMultipartUploadResponse response = subMinioClient.createMultipartUpload(bucketName, null, objectName, null, null);
        InitiateMultipartUploadResult result = response.result();
        String uploadId = result.uploadId();




        //对源文件进行分片
        File file = new File("D:\\data\\sharding2\\");
        File[] files = file.listFiles();
        List<Part> partETags = new ArrayList<>();

        long filePosition = 0; //文件位置，初始为0
        Part[] parts = new Part[1000];
        for (int i = 1 ; i <= files.length; i++) {
            //3.依次上传分片，每次上传携带uploadId
            FileInputStream fileInputStream = new FileInputStream(files[i-1]);
            //上传分片

            int available = fileInputStream.available();
            UploadPartResponse uploadPartResponse = subMinioClient.uploadPart(bucketName, null, objectName, fileInputStream, available, uploadId, i, null, null);
            String etag = uploadPartResponse.etag();

            parts[i-1] = new Part(i, etag);
        }

        //其他：查询分片数据subMinioClient.listMultipartUploads();
        /*ListPartsResponse listPartsResponse = subMinioClient.listParts("ai-model", null, objectName, 1000, 0, uploadId, null, null);
        int partNumber = 1;
        for (Part part : listPartsResponse.result().partList()) {
            parts[partNumber - 1] = new Part(partNumber, part.etag());
            partNumber++;
        }*/

        ObjectWriteResponse objectWriteResponse = subMinioClient.completeMultipartUpload(bucketName, null, objectName, uploadId, parts, null, null);
//        subMinioClient.getPresignedObjectUrl()

        //问题：文件是否一致

        //其他：查询分片数据 subMinioClient.listMultipart

    }

    public SubMinioClient initClient(){
        String endpoint= "http://172.16.0.16:9000/";
        String accessKey="rcmL8t0EfcmaGrEQ";
        String secretKey="0CDZzmRFlqLaRnoufn177wycXlin3lt1";
        String bucketName="ai-model";
        return new SubMinioClient(MinioAsyncClient.builder().endpoint(endpoint).credentials(accessKey,secretKey).build());
    }



    public String initTask(SubMinioClient subMinioClient){
        String bucketName="ai-model";
        String objectName = "sub/test/产品推广.pptx";
        try {
            CreateMultipartUploadResponse response = subMinioClient.createMultipartUpload(bucketName, null, objectName, null, null);
            return response.result().uploadId();
        } catch (NoSuchAlgorithmException | InsufficientDataException | IOException | InvalidKeyException | ServerException | XmlParserException | ErrorResponseException | InternalException | InvalidResponseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回临时带签名、过期时间一天、Get请求方式的访问URL
     *
     * @return
     */
    @SneakyThrows
    public String getPresignedObjectUrl(SubMinioClient subMinioClient,Map<String, String> queryParams) {
        return subMinioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket("ai-model")
                        .object("sub/test/产品推广.pptx")
                        .expiry(60 * 60 * 24)
                        .extraQueryParams(queryParams)
                        .build());
    }

    @SneakyThrows
    public Map<String, String> getPresignedPostFormData(SubMinioClient subMinioClient) {
        // 为存储桶创建一个上传策略，过期时间为7天
        PostPolicy policy = new PostPolicy("ai-model", ZonedDateTime.now().plusDays(1));
        // 设置一个参数key，值为上传对象的名称
        policy.addEqualsCondition("key", "sub/test/产品推广.pptx");
        // 添加Content-Type，例如以"image/"开头，表示只能上传照片，这里吃吃所有
        policy.addStartsWithCondition("Content-Type", MediaType.OCTET_STREAM.type());
        // 设置上传文件的大小 64kiB to 10MiB.
        //policy.addContentLengthRangeCondition(64 * 1024, 10 * 1024 * 1024);
        return subMinioClient.getPresignedPostFormData(policy);
    }





}
